const { envList } = require('../../envList');

// pages/me/index.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    openId: '',
    showUploadTip: false,
    userInfo: {}
  },

  onShow() {
   try {
    const { userInfo } = getApp().globalData;
    this.setData({
      userInfo
    });
   } catch (error) {
     
   }
  },

  gotoConfig() {
    wx.navigateTo({
      url: `/pages/config/index?openId=${this.data.openId || '123121'}`,
    });
  },

  getOpenId() {
    wx.showLoading({
      title: '',
    });
    wx.cloud
      .callFunction({
        name: 'quickstartFunctions',
        config: {
          env: 'mock-weather-6g2jv4s1cede9cfc'
        },
        data: {
          type: 'getOpenId',
        },
      })
      .then(async (resp) => {
        const isHaveUserRes = await wx.cloud
        .callFunction({
          name: 'quickstartFunctions',
          config: {
            env: 'mock-weather-6g2jv4s1cede9cfc'
          },
          data: {
            type: 'isHaveUser',
            _openId: resp.result.openid
          },
        })
        if (isHaveUserRes?.result?.list.length) {
           this.setData({
            haveGetOpenId: true,
            openId: resp.result.openid,
            userInfo: isHaveUserRes?.result?.list?.[0]
          });
          getApp().globalData.userInfo = isHaveUserRes?.result?.list?.[0]
          wx.hideLoading()
        } else {
          wx.getSetting({
            success:  async(res0) => {
              if (res0.authSetting['scope.userInfo']) {
                // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                wx.getUserInfo({
                  success: async (res) => {
                    this.setData({
                      haveGetOpenId: true,
                      openId: resp.result.openid,
                      userInfo: res.userInfo
                    });
                    getApp().globalData.userInfo = res.userInfo
                    wx.hideLoading();
                    wx.cloud
        .callFunction({
          name: 'quickstartFunctions',
          data: {
            type: 'createUser',
            userInfo: res.userInfo,
            _openId: resp.result.openid
          },
        })
                  }
                })
              }
            }
          })
        }
        // this.setData({
        //   haveGetOpenId: true,
        //   openId: resp.result.openid,
        // });
        // wx.hideLoading();
      })
      .catch((e) => {
        console.error(e)
        wx.showToast({
          title: '登录失败',
          icon: 'error'
        })
        wx.hideLoading();
      });
  },

  gotoWxCodePage() {
    wx.navigateTo({
      url: `/pages/exampleDetail/index?envId=${envList?.[0]?.envId}&type=getMiniProgramCode`,
    });
  },

  gotoLottery() {
    wx.navigateTo({
      url: `/pages/price/pages/index/index`,
    });
  }
});
